import React, { useEffect, useState } from "react";
import { Table, Button, Popconfirm, message, Form, Input, Modal } from "antd";
import {
  deleteBookType,
  getAllBookType,
  searchBookTypeByName,
  updateBookType,
} from "../../api/classfiy";

const { Item } = Form;
const { Search } = Input;

const Classfiy = () => {
  const [categories, setCategories] = useState<any>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<any>(null);
  const [form] = Form.useForm();

  const getData = async () => {
    const res: any = await getAllBookType();

    setCategories(
      res.data.map((item: { bookTypeId: string; name: string }) => ({
        key: item.bookTypeId,
        name: item.name,
      }))
    );
  };

  useEffect(() => {
    getData();
  }, []);

  const showModal = (category: any = null) => {
    setEditingCategory(category);
    setIsModalVisible(true);
    if (category) {
      form.setFieldsValue({ name: category?.name });
    } else {
      form.resetFields();
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingCategory(null);
  };

  const handleDelete = async (record: any) => {
 
    const res = await deleteBookType({ id: record.key });

    if (res.success) {
      message.success("分类已删除");
      getData();
    }
  };

  const handleFinish = async (values: any) => {
    if (editingCategory) {
      const res = await updateBookType({
        bookTypeId: editingCategory.key,
        name: values.name,
      });

      if (res.success) {
        getData();
        message.success("分类已更新");
      }
    } else {
      const newCategory = {
        key: categories.length + 1,
        ...values,
      };
      const res = await updateBookType(newCategory);

      if (res.success) {
        getData();
        message.success("分类已添加");
      }
    }
    setIsModalVisible(false);
    setEditingCategory(null);
  };

  const handleSearch = async (value: any) => {

    const res = await searchBookTypeByName({ name: value });

    if (res.success) {
      setCategories(res.data);
    }
  };

  const columns = [
    {
      title: "分类名称",
      dataIndex: "name",
      key: "name",
      sorter: (a: any, b: any) => a.name.localeCompare(b.name),
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_: any, record: any) => (
        <span>
          <Button
            type="primary"
            onClick={() => showModal(record)}
            style={{ marginRight: 8 }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除此分类?"
            onConfirm={() => handleDelete(record)}
          >
            <Button color="red">删除</Button>
          </Popconfirm>
        </span>
      ),
    },
  ];

  return (
    <div style={{ padding: "20px" }}>
      <Search
        placeholder="搜索分类"
        onSearch={handleSearch}
        style={{ marginBottom: 16, width: 300 }}
      />
      <Button
        type="primary"
        onClick={() => showModal()}
        style={{ marginBottom: 16, marginLeft: 16 }}
      >
        添加分类
      </Button>
      <Table
        columns={columns}
        dataSource={categories}
        pagination={{ pageSize: 10 }}
      />
      <Modal
        title={editingCategory ? "编辑分类" : "添加分类"}
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form form={form} onFinish={handleFinish} layout="vertical">
          <Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: "请输入分类名称" }]}
          >
            <Input />
          </Item>
          <Item>
            <Button type="primary" htmlType="submit">
              {editingCategory ? "更新" : "添加"}
            </Button>
          </Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Classfiy;
